package com.gec.content.service.impl;

import com.gec.content.service.ContentService;
import com.gec.mall.mapper.TbContentMapper;
import com.gec.mall.pojo.TbContent;
import com.gec.mall.pojo.TbContentExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: li
 * @Date: 2023/2/6
 * @PACKAGE_NAME:com.gec.content.service.impl
 * @Project_Name:mall-parent
 * @VERSION: 1.0.0
 */
@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private TbContentMapper contentMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<TbContent> getAllContent() {
        return contentMapper.selectByExample(null);
    }

    @Override
    public List<TbContent> getContentByCategoryId(Long categoryId) {

        //加入缓存代码
        List<TbContent> list = (List<TbContent>) redisTemplate.opsForHash().get("content", categoryId);
        if (list == null){ //首次加载
            System.out.println("查询数据库==========");
            TbContentExample example = new TbContentExample();
            TbContentExample.Criteria criteria = example.createCriteria();
            //有效广告
            criteria.andStatusEqualTo("1");

            criteria.andCategoryIdEqualTo(categoryId);

            //排序
            example.setOrderByClause("sort_order");
            list = contentMapper.selectByExample(example);

            redisTemplate.boundHashOps("content").put(categoryId, list);

        }else {
            System.out.println("从缓存中获取====================");
        }

        return list;
    }

    @Override
    public void addContent(TbContent tbContent) {
        contentMapper.insert(tbContent);
        //清楚缓存redis
        redisTemplate.boundHashOps("content").delete(tbContent.getCategoryId());
    }

    @Override
    public void delContentById(Long id) {
        TbContent tbContent = contentMapper.selectByPrimaryKey(id);
        redisTemplate.boundHashOps("content").delete(tbContent.getCategoryId());

        contentMapper.deleteByPrimaryKey(id);
    }
}
